package com.zzyl.serve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.common.utils.WechatUtil;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.serve.domain.*;
import com.zzyl.serve.dto.FamilyElderDto;
import com.zzyl.serve.dto.MemberLoginDto;
import com.zzyl.serve.mapper.*;
import com.zzyl.serve.service.IFamilyMemberService;
import com.zzyl.serve.vo.FamilyElderPageVo;
import com.zzyl.serve.vo.FamilyElderVo;
import com.zzyl.serve.vo.MemberLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 老人家属Service业务层处理
 *
 * @author liuyp
 * @date 2025-08-21
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private WechatUtil wechatUtil;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private static final List<String> nickNamePool = List.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");
    @Autowired
    private DataSourceTransactionManagerAutoConfiguration dataSourceTransactionManagerAutoConfiguration;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return familyMemberMapper.deleteById(id);
    }

    @Override
    public MemberLoginVo login(MemberLoginDto dto) {
        // 1. 向微信平台发请求获取openid
        String openid = wechatUtil.getOpenid(dto.getCode());
        // 2. 向微信平台发请求获取手机号
        String phone = wechatUtil.getPhone(dto.getPhoneCode());
        // 3. 根据微信账号openid，到数据库表里查询一下
        LambdaQueryWrapper<FamilyMember> wrapper = Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = familyMemberMapper.selectOne(wrapper);
        // 4. 判断是否查到家属信息了
        if (familyMember == null) {
            familyMember = new FamilyMember();
            // 给用户设置昵称，而不是使用了用户的微信昵称。昵称：从nickNamePool里随机取一个昵称，再拼接上手机号后4位
            familyMember.setName(nickNamePool.get(new Random().nextInt(nickNamePool.size())) + phone.substring(phone.length() - 4));
            familyMember.setOpenId(openid);
            familyMember.setPhone(phone);
            save(familyMember);
        } else {
            // 如果手机号 和 数据库里的手机号不同，则需要更新手机号
            if (!phone.equals(familyMember.getPhone())) {
                familyMember.setPhone(phone);
                updateById(familyMember);
            }
        }
        // 5. 准备返回值
        MemberLoginVo vo = new MemberLoginVo();
        vo.setNickName(familyMember.getName());
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", familyMember.getId());
        claims.put("name", familyMember.getName());
        vo.setToken(tokenService.createToken(claims));
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertFamilyEider(FamilyElderDto familyElderDto) {
        // 非空校验（身份证号、姓名、称呼为必填项）
        if (familyElderDto.getIdCard() == null || familyElderDto.getName() == null || familyElderDto.getRemark() == null) {
            throw new BaseException("身份证号、姓名、称呼为必填项");
        }

        // 检查是否已经存在相同的记录（根据身份证号、姓名、称呼判断）
        LambdaQueryWrapper<Elder> queryWrapper = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, familyElderDto.getIdCard())
                .eq(Elder::getStatus,1);

        if (elderMapper.selectCount(queryWrapper) <= 0) {
            throw new BaseException("老人家属未入住");
        }

        // 创建家属对象并保存
        Elder elder = elderMapper.selectOne(queryWrapper);
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setElderId(Integer.valueOf(String.valueOf(elder.getId())));
        familyMemberElder.setRemark(familyElderDto.getRemark());
        familyMemberElder.setCreateTime(new Date());
        familyMemberElder.setCreateBy(String.valueOf(UserThreadLocal.getUserId()));
        familyMemberElder.setFamilyMemberId(Integer.valueOf(String.valueOf(UserThreadLocal.getUserId())));


        // 保存到数据库
        return familyMemberElderMapper.insert(familyMemberElder);
    }

    @Override
    public List<FamilyElderVo> myfamily() {
        //准备数据，返回给客户端
        List<FamilyElderVo> list = new ArrayList<>();

        //获取当前老人家属id(条件)
        Long userId = UserThreadLocal.getUserId();

        //根据老人家属id从老人家属中间关系表中获取老人ids
        LambdaQueryWrapper<FamilyMemberElder> wrapper = Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, userId);

        //根据亲属id获取老人ids
        List<FamilyMemberElder> elders = familyMemberElderMapper.selectList(wrapper);
        if (elders==null||elders.size()==0){
            throw new BaseException("跳转");
        }

        //遍历老人id，查询老人name
        for (FamilyMemberElder elder : elders) {
            FamilyElderVo familyElderVo = new FamilyElderVo();

            familyElderVo.setId(Long.valueOf(String.valueOf(elder.getId())));
            familyElderVo.setFamilyMemberId(Long.valueOf(String.valueOf(elder.getFamilyMemberId())));
            familyElderVo.setElderName(elderMapper.selectById(elder.getElderId()).getName());
            familyElderVo.setElderId(Long.valueOf(String.valueOf(elder.getElderId())));
            list.add(familyElderVo);
        }

        return list;
    }



    @Override
    public List<FamilyElderPageVo> mylod(Integer pageNum, Integer pageSize) {
        // 在查询方法前调用PageHelper.startPage
        PageHelper.startPage(pageNum,  pageSize); // 页码，每页数量
        //查询当前用户id绑定的老人，从中间关系表获取
        Integer userId = Integer.valueOf(UserThreadLocal.getUserId().toString());
        LambdaQueryWrapper<FamilyMemberElder> wrapper = Wrappers.<FamilyMemberElder>lambdaQuery()
                .eq(FamilyMemberElder::getFamilyMemberId, userId);
        List<FamilyMemberElder> familyMemberElders = familyMemberElderMapper.selectList(wrapper);
        List<FamilyElderPageVo> list = new ArrayList<>();
        for (FamilyMemberElder familyMemberElder : familyMemberElders) {
            FamilyElderPageVo familyElderPageVo = new FamilyElderPageVo();
            Long elderId =Long.valueOf(familyMemberElder.getElderId());
            Elder elder = elderMapper.selectElderById(elderId);
            familyElderPageVo.setName(elder.getName());
            familyElderPageVo.setImage(elder.getImage());
            familyElderPageVo.setBedNumber(elder.getBedNumber());
            familyElderPageVo.setElderId(elder.getId());
            Long bedId = elder.getBedId();
            Bed bed = bedMapper.selectBedById(bedId);
            Room room = roomMapper.selectRoomById(bed.getRoomId());
            familyElderPageVo.setTypeName(room.getTypeName());
            LambdaQueryWrapper<Device> wrapper1 = Wrappers.<Device>lambdaQuery().eq(Device::getLocationType, 0)
                    .eq(Device::getBindingLocation, elder.getId());
            Device device = deviceMapper.selectOne(wrapper1);
            if (device != null) {
                familyElderPageVo.setIotId(device.getIotId());
                familyElderPageVo.setDeviceName(device.getDeviceName());
                familyElderPageVo.setProductKey(device.getProductKey());
            }
            familyElderPageVo.setMid(Long.valueOf(familyMemberElder.getFamilyMemberId()));
            familyElderPageVo.setMremark(familyMemberElder.getRemark());
            list.add(familyElderPageVo);
        }
        return list ;


}
}
